package com.hanyxx.thread.lock;

import lombok.SneakyThrows;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * synchronized 进行同步互斥控制
 * @author layman
 * @date 2021/2/9
 */
public class Demo02 {
    public static void main(String[] args) {
        Demo02Service service = new Demo02Service();
        Demo02ThreadA threadA = new Demo02ThreadA(service);
        Demo02ThreadB threadB = new Demo02ThreadB(service);

        threadA.setName("线程A");
        threadB.setName("线程B");

        threadA.start();
        threadB.start();
    }
}
class Demo02Service{
    private SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
    private Lock lock = new ReentrantLock();
    public /*synchronized*/ void methodA() throws InterruptedException {
        lock.lock();
        System.out.println(Thread.currentThread().getName()+" 开始执行methodA方法："+sdf.format(new Date(System.currentTimeMillis())));
        Thread.sleep(3000L);
        System.out.println(Thread.currentThread().getName()+" 结束执行methodA方法："+sdf.format(new Date(System.currentTimeMillis())));
        lock.unlock();
    }
    public /*synchronized*/ void methodB() throws InterruptedException {
        lock.lock();
        System.out.println(Thread.currentThread().getName()+" 开始执行methodB方法："+sdf.format(new Date(System.currentTimeMillis())));
        Thread.sleep(3000L);
        System.out.println(Thread.currentThread().getName()+" 结束执行methodB方法："+sdf.format(new Date(System.currentTimeMillis())));
        lock.unlock();
    }
}
class Demo02ThreadA extends  Thread{
    private Demo02Service service;
    public Demo02ThreadA(Demo02Service service){
        this.service = service;
    }
    @SneakyThrows
    @Override
    public void run() {
        service.methodA();
    }
}
class Demo02ThreadB extends  Thread{
    private Demo02Service service;
    public Demo02ThreadB(Demo02Service service){
        this.service = service;
    }
    @SneakyThrows
    @Override
    public void run() {
        service.methodB();
    }
}
